<template>
  <div id="answerResultPage">
    <a-card :bordered="false" class="result-card">
      <div class="result-header">
        <h1 class="result-title">测试结果</h1>
        <div class="result-timestamp">
          {{ dayjs(data.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </div>
      </div>

      <a-divider />

      <a-row :gutter="24">
        <a-col :span="data.resultPicture ? 16 : 24">
          <div class="result-content">
            <h2 class="result-name">{{ data.resultName }}</h2>
            <div class="result-score">
              <a-progress
                :percent="data.resultScore || 0"
                :stroke-color="getScoreColor(data.resultScore)"
                :track-color="'rgba(var(--primary-6), 0.1)'"
              />
              <span class="score-value">{{ data.resultScore || 0 }}分</span>
            </div>

            <div class="result-desc">{{ data.resultDesc }}</div>

            <a-divider />

            <div class="detail-section">
              <h3>答题详情</h3>
              <a-descriptions :column="1" layout="vertical" bordered>
                <a-descriptions-item label="应用类型">
                  <a-tag
                    >{{
                      data.appType !== undefined
                        ? typedAppTypeMap[data.appType]
                        : "未知"
                    }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="评分策略">
                  <a-tag color="arcoblue">
                    {{
                      data.scoringStrategy !== undefined
                        ? typedScoringStrategyMap[data.scoringStrategy]
                        : "未知"
                    }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="我的答案">
                  <a-space direction="vertical">
                    <a-tag
                      v-for="(choice, index) in formatChoices(data.choices)"
                      :key="index"
                      color="arcoblue"
                    >
                      {{ choice }}
                    </a-tag>
                  </a-space>
                </a-descriptions-item>
              </a-descriptions>
            </div>

            <div class="user-info">
              <h3>答题人信息</h3>
              <a-space>
                <a-avatar
                  :size="36"
                  :image-url="data.user?.userAvatar"
                  :style="{ marginRight: '8px', backgroundColor: '#3370ff' }"
                >
                  {{ getUserInitial(data.user?.userName) }}
                </a-avatar>
                <div class="user-detail">
                  <div class="user-name">
                    {{ data.user?.userName ?? "无名用户" }}
                  </div>
                  <div class="user-id">ID: {{ data.user?.id }}</div>
                </div>
              </a-space>
            </div>
          </div>
        </a-col>

        <a-col :span="8" v-if="data.resultPicture">
          <div class="result-image">
            <a-image width="100%" :src="data.resultPicture" :preview="false" />
          </div>
        </a-col>
      </a-row>

      <a-divider />

      <div class="action-area">
        <a-space size="large">
          <a-button
            type="primary"
            shape="round"
            size="large"
            :href="`/answer/do/${data.appId}`"
          >
            <template #icon>
              <icon-refresh />
            </template>
            重新测试
          </a-button>
          <a-button 
            shape="round" 
            size="large" 
            @click="navigateToWrongQuestions"
          >
            <template #icon>
              <icon-exclamation-circle />
            </template>
            查看错题
          </a-button>
          <a-button shape="round" size="large" @click="shareResult">
            <template #icon>
              <icon-share-alt />
            </template>
            分享结果
          </a-button>
        </a-space>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, watchEffect, withDefaults } from "vue";
import API from "@/api";
import { getUserAnswerVoByIdUsingGet } from "@/api/userAnswerController";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from "../../constant/app";
import { IconRefresh, IconShareAlt, IconExclamationCircle } from "@arco-design/web-vue/es/icon";

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => {
    return "";
  },
});

const router = useRouter();

const data = ref<API.UserAnswerVO>({});

// 确保类型映射有正确的类型定义
type AppTypeMap = {
  [key: number]: string;
};

type ScoringStrategyMap = {
  [key: number]: string;
};

// 类型断言
const typedAppTypeMap = APP_TYPE_MAP as AppTypeMap;
const typedScoringStrategyMap = APP_SCORING_STRATEGY_MAP as ScoringStrategyMap;

/**
 * 根据分数返回对应的颜色
 * @param score 分数
 */
const getScoreColor = (score: number = 0) => {
  if (score >= 80) return "#00b42a"; // 绿色
  if (score >= 60) return "#165dff"; // 蓝色
  if (score >= 40) return "#ff7d00"; // 橙色
  return "#f53f3f"; // 红色
};

/**
 * 格式化选择答案
 */
const formatChoices = (choices: string[] | undefined) => {
  if (!choices || choices.length === 0) return ["暂无数据"];
  return choices;
};

/**
 * 获取用户名首字母（用于头像显示）
 */
const getUserInitial = (userName: string | undefined) => {
  if (!userName) return "?";
  return userName.charAt(0).toUpperCase();
};

/**
 * 分享结果
 */
const shareResult = () => {
  // 复制当前页面URL到剪贴板
  const currentUrl = window.location.href;
  navigator.clipboard
    .writeText(currentUrl)
    .then(() => {
      message.success("结果链接已复制到剪贴板，可以分享给好友了！");
    })
    .catch(() => {
      message.error("复制链接失败，请手动复制地址栏URL");
    });
};

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.id) {
    return;
  }
  const res = await getUserAnswerVoByIdUsingGet({
    id: props.id as any,
  });
  if (res.data.code === 0) {
    data.value = res.data.data as any;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 导航到错题页面
 */
const navigateToWrongQuestions = () => {
  router.push('/answer/wrong_questions');
};
</script>

<style scoped>
#answerResultPage {
  padding: 16px;
}

.result-card {
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.result-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--color-text-1);
  margin: 0;
}

.result-timestamp {
  color: var(--color-text-3);
  font-size: 14px;
}

.result-content {
  padding: 16px 0;
}

.result-name {
  font-size: 28px;
  font-weight: 700;
  color: var(--color-text-1);
  margin-bottom: 24px;
  line-height: 1.2;
}

.result-score {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.score-value {
  margin-left: 16px;
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-1);
}

.result-desc {
  font-size: 16px;
  color: var(--color-text-2);
  line-height: 1.6;
  margin-bottom: 32px;
  white-space: pre-line;
}

.detail-section,
.user-info {
  margin-bottom: 32px;
}

.detail-section h3,
.user-info h3 {
  font-size: 18px;
  margin-bottom: 16px;
  font-weight: 600;
  color: var(--color-text-1);
}

.result-image {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-info {
  margin-top: 32px;
}

.user-detail {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 600;
  color: var(--color-text-1);
}

.user-id {
  font-size: 13px;
  color: var(--color-text-3);
}

.action-area {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
</style>
